// 2025/10/11: 首个版本

using System;
using System.Xml;
using System.IO;
using System.Text;
using ASEva;
using ASEva.UIAvalonia;
using ASEva.Utility;

namespace CommonSource
{
    partial class RunStandaloneTaskDetails : DialogPanel
    {
        public RunStandaloneTaskDetails() // For designer
        {
            InitializeComponent();
            language = new LanguageSwitch(Resources, AgencyLocal.GetAppLanguage());
        }

        public RunStandaloneTaskDetails(String taskClassID, String taskConfig, String taskReturnValue, String iconResourceName = null)
        {
            InitializeComponent();
            SetResizableMode(500, 300, 800, 500);
            Icon = ResourceLoader.Load(iconResourceName)?.ToAvaloniaWindowIcon();
            language = new LanguageSwitch(Resources, AgencyLocal.GetAppLanguage());
            Title = language["title"];

            String niceConfig, niceReturnVal;
            checkIsXml(taskConfig, out niceConfig);
            checkIsXml(taskReturnValue, out niceReturnVal);

            textID.Text = taskClassID;
            textConfig.Text = niceConfig;
            textReturnVal.Text = niceReturnVal;
        }

        private bool checkIsXml(String str, out String niceXmlString)
        {
            niceXmlString = "";
            if (str == null) str = "";
            if (str.StartsWith("<?xml"))
            {
                var xml = new XmlDocument();
                try
                {
                    xml.LoadXml(str);
                    niceXmlString = toNiceString(xml);
                    return true;
                }
                catch (Exception) {}
            }
            return false;
        }

        private String toNiceString(XmlDocument xml)
        {
            if (xml == null) return "";

            var memoryStream = new MemoryStream();

            var settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "    ";

            var xmlWriter = XmlWriter.Create(memoryStream, settings);
            xml.Save(xmlWriter);
            xmlWriter.Close();

            memoryStream.Position = 3; // BOM
            var data = new byte[memoryStream.Length - 3];
            memoryStream.Read(data, 0, (int)memoryStream.Length - 3);
            memoryStream.Close();

            return Encoding.UTF8.GetString(data);
        }

        private LanguageSwitch language;
    }
}